package com.company.bookstore.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.company.bookstore.entities.user_admin_module.Admin;
import com.company.bookstore.exception.user_admin_module.CustomException;
import com.company.bookstore.mapper.user_admin_module.AdminMapper;
import com.company.bookstore.qo.user_admin_module.AdminQo;
import com.company.bookstore.service.user_admin_module.AdminService;
import com.company.bookstore.validator.user_admin_module.AdminQoRegisterValidator;
import com.company.bookstore.validator.user_admin_module.AdminQoUpdateValidator;
import com.company.bookstore.validator.user_admin_module.ValidatorFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * <p>
 * 管理员表 服务实现类
 * </p>
 *
 * @author 吴经纶
 * @blame Android Team
 * @since 2020-08-28
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements AdminService {
    @Resource
    BCryptPasswordEncoder passwordEncoder;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper<Admin> userQueryWrapper= new QueryWrapper<Admin>().eq("admin_name",username);
        return getOne(userQueryWrapper);
    }
    
    @Override
    public boolean insertAdmin(String adminName , String password,Integer fkRoleId){
       return save(Admin.builder().adminName(adminName).password(password).enabled(1).deleted(0).fkRoleId(fkRoleId).build());
    }

    @Override
    public boolean updateAdminQo(AdminQo adminQo) throws NoSuchMethodException, CustomException {
       if (ValidatorFactory.Invoke(AdminQoUpdateValidator.class.getName(),adminQo)){
//            反射字段 并新建 对应 类
            try {
                Admin admin = Admin.builder().build();
                BeanUtils.copyProperties(adminQo,admin);
                if (adminQo.getPassword()!=null){
                    admin.setPassword(passwordEncoder.encode(adminQo.getPassword()));
                }
                updateById(admin);
                return true;
            }catch (Exception e){
                e.printStackTrace();
                return false;
            }
        }
        return false;
    }
}
